﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UFSSServerClasses
{
    public static class TokenHandler
    {
        private static Dictionary<string, int> TokenListByToken = new Dictionary<string,int>();  //Two lists needed to find userid based on token
        private static Dictionary<int, string> TokenListByUserID = new Dictionary<int,string>(); //and to find token based on userid, both have same data just reversed
        static public bool checkToken(int userid, string key)
        {
            try
            {
                if (TokenListByToken[key] == userid)
                    return true;
                return false;
            }
            catch
            {
                return false;
            }
        }
        static public string AddToken(int userid)  // Adds a token to both lists if none already exist.
        {                                 // if token already exists, it's deleted and replaced with a new one.
            if (userid < 0)//invalid userid
                return null;
            try
            {
                if (!TokenListByToken.ContainsValue(userid))
                {
                    string token = Guid.NewGuid().ToString();
                    TokenListByUserID.Add(userid, token);
                    TokenListByToken.Add(token, userid);
                    return token;
                }
                else
                {
                    RemoveToken(TokenListByUserID[userid]);
                    return AddToken(userid);
                }
            }
            catch
            {
                return null;
            }
        }
        static public bool RemoveToken(string token)
        {
            if(TokenListByToken.ContainsKey(token))
            {
                int userid = TokenListByToken[token];
                TokenListByUserID.Remove(userid);
                TokenListByToken.Remove(token);
                return true;
            }
            else
                return false;
        }
    }
}
